'use strict'
const path = require('path')
const autoprefixer = require('autoprefixer')
const pxtorem = require('postcss-pxtorem')
function resolve(dir) {
  return path.join(__dirname, dir)
}

const CompressionWebpackPlugin = require('compression-webpack-plugin')
const productionGzipExtensions = ['js', 'css']
const isDev = process.env.NODE_ENV === 'development'
const port = process.env.port || process.env.npm_config_port || 8888 // dev port
const publicPath = process.env.VUE_APP_PUBLIC_PATH
const target = process.env.VUE_APP_TARGET
module.exports = {
  publicPath: publicPath,
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    port: port || '0.0.0.0:8888',
    hot: false,
    disableHostCheck: false,
    proxy: {
      '/api': {
        target,
        changeOrigin: true,
        pathRewrite: {
          '^/api': ''
        }
      }
    }
  },
  // configureWebpack: {
  //     externals: {
  //         'MathLive': 'MathLive'
  //     }
  // },
  configureWebpack: config => {
    // config.externals['MathLive'] = 'MathLive'
    /* config.plugins.push(
      new NotifierPlugin()
    )*/
    if (!isDev) {
      // 取消console打印
      config.optimization.minimizer[0].options.terserOptions.compress.drop_console = true
      config.plugins.push(
        new CompressionWebpackPlugin({
          algorithm: 'gzip',
          test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
          threshold: 10240,
          minRatio: 0.8
        })
      )
    }
  },

  css: {
    loaderOptions: {
      postcss: {
        plugins: [
          autoprefixer(),
          pxtorem({
            rootValue: 192,
            propList: ['*'],
            selectorBlackList: ['public_print'],
            exclude: e => {
              // 排除某些文件
              if (/src(\\|\/)views(\\|\/)prediction/.test(e) || /src(\\|\/)views(\\|\/)trumpet/.test(e)) { // 文件夹或者文件的路径
                return true
              }
            }
          })
        ]
      },
      sass: {
        data: `@import "./src/styles/theme.scss";@import "./src/styles/variables.scss";` // 存放需要全局注入的scss，可以全局使用变量
      }
    }
  },

  chainWebpack(config) {
    // config.plugin('preload').tap(() => [
    //   {
    //     rel: 'preload',
    //     // to ignore runtime.js
    //     fileBlacklist: [/\.map$/, /hot-update\.js$/, /runtime\..*\.js$/],
    //     include: 'initial'
    //   }
    // ]);
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test
    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === 'development', config => config.devtool('cheap-source-map'))

    config.when(process.env.NODE_ENV !== 'development', config => {
      config
        .plugin('ScriptExtHtmlWebpackPlugin')
        .after('html')
        .use('script-ext-html-webpack-plugin', [
          {
            // `runtime` must same as runtimeChunk name. default is `runtime`
            inline: /runtime\..*\.js$/
          }
        ])
        .end()
      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          libs: {
            name: 'chunk-libs',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial' // only package third parties that are initially dependent
          },
          elementUI: {
            name: 'chunk-elementUI', // split elementUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
          },
          commons: {
            name: 'chunk-commons',
            test: resolve('src/components'), // can customize your rules
            minChunks: 3, //  minimum common number
            priority: 5,
            reuseExistingChunk: true
          }
        }
      })
      config.optimization.runtimeChunk('single')
    })
  }
}
